package com.it.tanhua.dubbo.server.apiImpl;

import com.alibaba.dubbo.config.annotation.Service;
import com.it.tanhua.dubbo.server.api.FriendCircleApi;
import com.it.tanhua.dubbo.server.pojo.Album;
import com.it.tanhua.dubbo.server.pojo.Publish;
import com.it.tanhua.dubbo.server.pojo.TimeLine;
import com.it.tanhua.dubbo.server.pojo.Users;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * @author ADMIN
 * @date 2021/8/19 23:51
 */
@Service(version = "1.0.0")
@Slf4j
public class FriendCircleApiImpl implements FriendCircleApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean savePublish(Publish publish) {
    //非空校验
        if (ObjectUtils.isEmpty(publish)) {
            return false;
        }
        try {
            publish.setCreated(System.currentTimeMillis());
            publish.setId(ObjectId.get());
            //查看权限
            publish.setSeeType(1);
            //保存动态信息
            mongoTemplate.save(publish);
            //写入到自己的相册表中
            Album album = new Album();
            album.setId(ObjectId.get());
            album.setCreated(System.currentTimeMillis());
            album.setPublishId(publish.getId());
            mongoTemplate.save(album, "quanzi_album_" + publish.getUserId());
            //查询当前用户好友的数据,将动态数据写入到好友的时间线
            Query query = Query.query(Criteria.where("userId").is(publish.getUserId()));
            List<Users> users = mongoTemplate.find(query, Users.class);
            for (Users user : users) {
                TimeLine timeLine = new TimeLine();
                timeLine.setId(ObjectId.get());
                timeLine.setPublishId(publish.getId());
                timeLine.setUserId(publish.getUserId());
                timeLine.setDate(System.currentTimeMillis());
                mongoTemplate.save(timeLine, "quanzi_time_line_" + user.getFriendId());
            }

            return true;
        } catch (Exception e) {
            log.error("savePublish::{}", e.getMessage());
            //todo 事务回滚
            return false;
        }
    }
}
